package com.itzb.asone.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpUtil {
	
	private static Logger logger = Logger.getLogger(HttpUtil.class); 
	
	/**
	 * 
	 * @param url
	 * @param params
	 */
	public static String post(String url,Map<String,String> params) {
		
		logger.debug("post send url:" + url);
		logger.debug("post send params:" + params);
		String result = "";
		try {
			HttpClient client = new HttpClient();
			PostMethod postMethod = new PostMethod(url);
			postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
			NameValuePair[] data = null;
			if(params == null){
				data = new NameValuePair[0];
			} else {
				data = new NameValuePair[params.size()];
				Set<String> set = params.keySet();
				int index = 0;
				for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
					String key = iterator.next();
					data[index] = new NameValuePair(key,params.get(key));
					index ++ ;
				}
			}
			postMethod.setRequestBody(data);
			client.executeMethod(postMethod);
			result = new String(postMethod.getResponseBodyAsString().getBytes("UTF-8"));
			logger.debug("post send result:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static void main(String[] a) {
		try {
			System.out.println(HttpUtil.post("http://asone.qianxunclub.com//asone-api/api/getblogseting",null));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
